import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/note_db_provider.dart';
import 'package:flutter_douban/main_page/home/video/window_video_page.dart';
import 'package:flutter_douban/model/active_big_model.dart';
import 'package:flutter_douban/main.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:like_button/like_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'note_detail_page.dart';

class ActiveCardView extends StatefulWidget {
  final ActiveBigModel model;
  const ActiveCardView({Key? key,required this.model}) : super(key: key);

  @override
  _ActiveCardViewState createState() => _ActiveCardViewState();
}

class _ActiveCardViewState extends State<ActiveCardView> {

  Future<bool> onLikeButtonTapped(bool isLiked) async {
    NoteDbProvider provider = new NoteDbProvider();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    if (numberId == null) {
      Fluttertoast.showToast(
          msg: "请先登录~",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black87,
          textColor: Colors.white,
          fontSize: 14.0);
      return widget.model.note!.is_collection!;
    }

    if (widget.model.note!.is_collection == true) {
      provider.delete(int.parse(widget.model.note!.id!), numberId);
    } else {
      provider.insert(widget.model.note!, numberId);
    }

    /// 延时更新数据
    Future.delayed(const Duration(milliseconds: 500), () {
      EventBusUtil.fire(CacheNoteEvent(CacheNoteEvent.cacheNoteIn));
    });
    return !widget.model.note!.is_collection!;
  }

  @override
  Widget build(BuildContext context) {
    String _imageStr = '';
    if (widget.model.activity != null) {
      _imageStr = 'assets/images/common/icon_feed_picid@2x.png';
    } else {
      if (widget.model.note!.video_url == null) {
        _imageStr = 'assets/images/common/icon_feed_picid@2x.png';
      } else {
        _imageStr = 'assets/images/common/cell_video_play@2x.png';
      }
    }

    return InkWell(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Stack(
            children: [
              Container(
                  color: AppColors.page,
                  child: ClipRRect(
                    child: CachedNetworkImage(
                      imageUrl: widget.model.activity != null
                          ? widget.model.activity!.image!
                          : widget.model.note!.image_u!,
                      fit: BoxFit.cover,
                    ),
                    borderRadius: BorderRadius.circular(6),
                  )),
              Positioned(
                  right: 10,
                  top: 10,
                  child: Image.asset(
                    _imageStr,
                    width: 28,
                    height: 28,
                  ))
            ],
          ),
          Container(
            padding: EdgeInsets.all(5),
            child: Text(
              widget.model.activity != null
                  ? widget.model.activity!.name!
                  : widget.model.note!.title!,
              style: TextStyle(
                color: AppColors.black,
                fontSize: 14,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 5, right: 10, bottom: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[_leftView(), _joinView()],
            ),
          )
        ],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          if (widget.model.note?.video_url?.isNotEmpty == true) {
            return WindowVideoPage(
              playType: PlayType.network,
              dataSource: widget.model.note!.video_url!,
              id: int.parse(widget.model.note!.id!),
            );
          } else {
            return NoteDetailPage(
              id: int.parse(widget.model.note!.id!),
            );
          }
        }));
        // Navigator.of(context).push(MaterialPageRoute(builder: (_) => WindowVideoPage(playType: PlayType.network, dataSource:model.note!.video_url!,)));
      },
    );
  }

  Widget _leftView() {
    return Row(
      children: [
        Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            color: AppColors.page,
            borderRadius: BorderRadius.circular(12),
          ),
          child: ClipOval(
            child: FadeInImage.assetNetwork(
              placeholder: 'assets/images/common/lazy-1.png',
              image: widget.model.activity != null
                  ? widget.model.activity!.author!.p!
                  : widget.model.note!.author!.p!,
              fit: BoxFit.cover,
            ),
          ),
        ),
        SizedBox(
          width: 5,
        ),
        Container(
          width: 60,
          child: Text(
            widget.model.activity != null
                ? widget.model.activity!.author!.n!
                :widget.model.note!.author!.n!,
            style: TextStyle(fontSize: 11, color: AppColors.qianTextColor),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    );
  }

  Widget _joinView() {
    if (widget.model.activity != null) {
      return Row(
        children: [
          FadeInImage.assetNetwork(
            width: 14,
            height: 14,
            placeholder: 'assets/images/common/lazy-1.png',
            image: widget.model.activity!.action_icon!,
            fit: BoxFit.cover,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            widget.model.activity!.action_title!,
            style: TextStyle(fontSize: 13, color: Colors.black),
          ),
        ],
      );
    } else {
      return LikeButton(
        size: 16,
        likeCount: widget.model.note!.like_count!,
        isLiked: widget.model.note!.is_collection,
        countBuilder: (int? count, bool isLiked, String text) {
          Widget result;
          if (isLiked == false) {
            result = Text(
              text,
              style: TextStyle(color: AppColors.qianTextColor, fontSize: 12),
            );
          } else
            result = Text(
              text,
              style: TextStyle(color: Colors.black87, fontSize: 12),
            );
          return result;
        },
        likeBuilder: (bool isLiked) {
          return Image.asset(
              'assets/images/common/question_comment_unlike_7@2x.png',
              color: isLiked == true ? AppColors.yellow : Colors.grey,
              width: 18,
              height: 18);
        },
        likeCountAnimationType: widget.model.note!.is_collection == true
            ? LikeCountAnimationType.part
            : LikeCountAnimationType.none,
        likeCountPadding: const EdgeInsets.only(left: 5.0),
        onTap: onLikeButtonTapped,
      );
    }
  }
}


